package cn.thornbird.orgsync.service.impl;

import cn.thornbird.orgsync.entity.LoginLog;
import cn.thornbird.orgsync.entity.User;
import cn.thornbird.orgsync.exception.NotFoundException;
import cn.thornbird.orgsync.model.PageList;
import cn.thornbird.orgsync.model.combined.LoginLogObject;
import cn.thornbird.orgsync.repository.LoginLogRepository;
import cn.thornbird.orgsync.repository.UserRepository;
import cn.thornbird.orgsync.repository.specification.LoginLogSpecification;
import cn.thornbird.orgsync.service.LoginLogService;
import cn.thornbird.orgsync.vo.request.LoginLogQueryRequest;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class LoginLogServiceImpl extends BaseService<LoginLogRepository, LoginLog> implements LoginLogService {

    private final LoginLogRepository loginLogRepository;

    private final UserRepository userRepository;

    @Override
    public LoginLogObject find(String id) throws NotFoundException {
        LoginLogObject loginLogObject = new LoginLogObject();
        LoginLog loginLog = findFirstById(loginLogRepository, id);
        User user = userRepository.findFirstById(loginLog.getUserId());
        loginLogObject.setLoginLog(loginLog);
        loginLogObject.setUser(user);
        return loginLogObject;
    }

    @Override
    public PageList<LoginLog> query(LoginLogQueryRequest loginLogQueryRequest, Integer pageNumber, Integer pageSize) {
        Sort sort = Sort.by(Sort.Order.desc("createdAt"));
        Pageable pageable = PageList.generatePageable(pageNumber, pageSize, sort);
        Page<LoginLog> page = loginLogRepository.findAll(new LoginLogSpecification(loginLogQueryRequest), pageable);
        return PageList.convertPage(page);
    }

}
